package cz.data.common.mark.manage;

import com.alibaba.fastjson.JSONObject;
import cz.data.common.support.FormatConstant;
import cz.data.common.support.db.core.DbColumn;
import cz.data.common.support.db.core.DbTable;
import cz.data.common.support.metadata.OracleDataTypeEnum;
import cz.data.common.utils.ThrowableUtil;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

public class OracleManageDialect implements JdbcManageDialect {
    @Override
    public String properties(DbTable table, Properties properties) {
        return "";
    }

    @Override
    public void preProcessData(DbTable table, JSONObject record) {
        List<DbColumn> columns = table.getColumns();
        for (DbColumn column : columns) {
            String colName = column.getColName();
            Object value = record.get(colName);
            if (Objects.nonNull(value)) {
                OracleDataTypeEnum dataTypeEnum = OracleDataTypeEnum.match(column.getDataType());
                switch (dataTypeEnum) {
                    case CHAR:
                    case VARCHAR:
                        record.put(colName, value.toString());
                        break;
                    case DATE:
                    case DATETIME:
                    case TIMESTAMP:
                        if (value instanceof String) {
                            Date date = ThrowableUtil.callable(
                                    () -> DateUtils.parseDate(value.toString(), FormatConstant.DATE_FORMATS),
                                    false);
                            if (Objects.nonNull(date)) {
                                record.put(colName, date);
                            }
                        } else if (value instanceof Long) {
                            record.put(colName, new Date((Long) value));
                        }
                        break;
                    case NUMBER:
                        double doubleValue = NumberUtils.toDouble(value.toString());
                        record.put(colName, doubleValue);
                        break;
                }
            }
        }
    }
}
